package com.example.MyThread.exercises02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Jason
 * @PACKAGE_NAME com.example.MyThread.exercises01
 * @Description 售卖门票
 * @date 2023-12-11 9:11
 */
public class BuyTickets extends Thread {
    static int gifts = 100;

    static Lock lock = new ReentrantLock();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public BuyTickets(String name) {
        super(name);
    }

    @Override

    public void run() {
        while (true) {
            //lock锁
            lock.lock();
            try {
                if (gifts > 10) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    gifts--;
                    System.out.println(getName() + "送出一份，剩余礼品数:" + gifts);
                } else {
                    System.out.println("礼品已售罄" + gifts);
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
